package com.jwdf.uda.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.bean.UploadImage;
import com.jwdf.uda.databinding.FragmentCmtListBinding;
import com.jwdf.uda.event.DialogDismissEvent;
import com.jwdf.uda.event.ReplyDetailEvent;
import com.jwdf.uda.event.ReplyDetailItemClickEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.QuizReplyDelCommentAction;
import com.jwdf.uda.http.action.ReplyGetCommentListAction;
import com.jwdf.uda.http.action.ReplyLikeCommentAction;
import com.jwdf.uda.ui.activity.presenter.ReplyAddCmtPresenter;
import com.jwdf.uda.ui.activity.view.IReplyCommentAddView;
import com.jwdf.uda.ui.adapter.ReplyCmtAdapter;
import com.jwdf.uda.ui.adapter.item.ReplyDetailItem;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.utils.ClipUtils;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.StringUtils;
import com.jwdf.uda.utils.ToastUtils;
import com.jwdf.uda.view.XListView;
import com.jwdf.uda.view.dialog.ChoiceDialog;
import com.jwdf.uda.view.dialog.CommentDialog;
import com.jwdf.uda.view.dialog.ConfirmDialog;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Response;

/**
 * Created by Administrator on 2016/10/17.
 */
public class ReplyAnswerCmtActivity extends AbsTitleBarActivity {
    private static final String EXTRA_ANSWER_ID = "answer_id";
    private final static String EXTRA_ATCOMMENT_ID = "atCommentId";
    private final static String EXTRA_ATNICKNAME = "atNickname";
    private static final String EXTRA_ANSWER_TYPE = "answer_type";

    public static void startActivity(Context context, int answerId, PbBean.PbSignNavType type) {
        ReplyAnswerCmtActivity.startActivity(context, answerId, -1, null, type);
    }

    public static void startActivity(Context context, int answerId, int atCommentId, String atNickname, PbBean.PbSignNavType type) {
        Intent intent = new Intent(context, ReplyAnswerCmtActivity.class);
        intent.putExtra(EXTRA_ANSWER_ID, answerId);
        intent.putExtra(EXTRA_ATCOMMENT_ID, atCommentId);
        intent.putExtra(EXTRA_ATNICKNAME, atNickname);
        intent.putExtra(EXTRA_ANSWER_TYPE, type);
        context.startActivity(intent);
    }


    @Override
    protected String getTopTitle() {
        return getString(R.string.title_comment);
    }

    private int answerId;
    private int atCommentId;
    private String atNickname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        answerId = getIntent().getIntExtra(EXTRA_ANSWER_ID, -1);
        atCommentId = getIntent().getIntExtra(EXTRA_ATCOMMENT_ID, -1);
        atNickname = StringUtils.filterNullAndTrim(getIntent().getStringExtra(EXTRA_ATNICKNAME));
        super.onCreate(savedInstanceState);
    }

    @Override
    protected Bundle onPutArguments() {
        Bundle args = new Bundle();
        args.putInt(EXTRA_ANSWER_ID, answerId);
        args.putInt(EXTRA_ATCOMMENT_ID, atCommentId);
        args.putString(EXTRA_ATNICKNAME, atCommentId > 0 ? getString(R.string.title_comment_at, atNickname) : "");
        args.putSerializable(EXTRA_ANSWER_TYPE, getIntent().getSerializableExtra(EXTRA_ANSWER_TYPE));
        return args;
    }

    @Override
    protected BaseFragment onCreateContentFragment() {
        return new CmtListFragment();
    }

    public static class CmtListFragment extends BaseFragment implements IReplyCommentAddView {
        private FragmentCmtListBinding mDataBinding;
        private ReplyCmtAdapter mAdapter;
        private CommentDialog mCmtDlg;
        private ReplyAddCmtPresenter mPresenter;
        private final static int CODE_REPLY = 1;
        private final static int CODE_COPY = 2;
        private final static int CODE_DEL = 3;
        private ChoiceDialog mCommentDialog;
        private ConfirmDialog mDelCommentDialog;
        private int replyId;
        private int atCommentId;
        private String atNickname;
        private PbBean.PbSignNavType mReplyType;

        private XListView.IXListViewListener mIXListener = new XListView.IXListViewListener() {
            @Override
            public void onRefresh(XListView xListView) {
                requestData(true);
            }

            @Override
            public void onLoadMore(XListView xListView) {
                requestData(false);
            }
        };

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            mDataBinding = FragmentCmtListBinding.inflate(inflater, container, false);
            initViews();
            requestData(true);
            return mDataBinding.getRoot();
        }

        private void initViews() {
            replyId = getArguments().getInt(EXTRA_ANSWER_ID);
            atCommentId = getArguments().getInt(EXTRA_ATCOMMENT_ID);
            atNickname = getArguments().getString(EXTRA_ATNICKNAME, "");
            mReplyType = (PbBean.PbSignNavType) getArguments().getSerializable(EXTRA_ANSWER_TYPE);
            mPresenter = new ReplyAddCmtPresenter(this, replyId, mReplyType);
            mDataBinding.commonListView.addHeaderView(createHeaderView());
            mDataBinding.commonListView.setPullRefreshEnable(true);
            mDataBinding.commonListView.setXListViewListener(mIXListener);
            mDataBinding.cmtBarLayout.setOnClickListener(createOnCmtListener());
            mAdapter = new ReplyCmtAdapter(getActivity());
            mDataBinding.commonListView.setAdapter(mAdapter);
            EventBusUtil.registerEvent(this);
            EventBusUtil.registerEvent(mAdapter);
        }

        @Override
        public void onDestroyView() {
            EventBusUtil.unregisterEvent(this);
            EventBusUtil.unregisterEvent(mAdapter);
            super.onDestroyView();
        }

        public void onEventMainThread(ReplyDetailEvent event) {
            switch (event.getEvent()) {
                case ReplyDetailEvent.EVENT_LIKE_COMMENT:
                case ReplyDetailEvent.EVENT_UNLIKE_COMMENT:
                    doLikeAction(event);
                    break;
                case ReplyDetailEvent.EVENT_COMMENT_ADD:
                    requestData(true);
                    break;
            }
        }

        private void doCopyContentAction(String content) {
            ClipUtils.copy(getActivity(), StringUtils.filterNullAndTrim(content));
            ToastUtils.show(getContext(), R.string.toast_copy_success);
        }

        private void showCommentChoiceDialog(final PbBean.PbBaseComment comment, boolean isAuthor) {
            mCommentDialog = new ChoiceDialog(getActivity());
            List<ChoiceDialog.ChoiceItem> items = new ArrayList<>();
            if (isAuthor) {
                items.add(new ChoiceDialog.ChoiceItem(CODE_COPY, getString(R.string.dialog_choice_copy)));
                items.add(new ChoiceDialog.ChoiceItem(CODE_DEL, getString(R.string.dialog_choice_del)));
            } else {
                items.add(new ChoiceDialog.ChoiceItem(CODE_REPLY, getString(R.string.dialog_choice_reply)));
                items.add(new ChoiceDialog.ChoiceItem(CODE_COPY, getString(R.string.dialog_choice_copy)));
            }
            mCommentDialog.setChoiceItems(items);
            mCommentDialog.setCallbackListener(new ChoiceDialog.CallbackListener() {
                @Override
                public void onItemClick(ChoiceDialog.ChoiceItem item) {
                    if (comment == null)
                        return;
                    switch (item.getCode()) {
                        case CODE_REPLY:
                            mCmtDlg = new CommentDialog(getContext(), comment.getId(), comment.getUserInfo().getNickname(), new CommentDialog.CallbackListener() {
                                @Override
                                public void onCmtSubmit(int commentId) {
                                    onAddCommentAction(commentId);
                                }
                            });
                            mCmtDlg.show();
                            break;
                        case CODE_COPY:
                            doCopyContentAction(comment.getContent());
                            break;
                        case CODE_DEL:
                            showDelCommentDialog(comment.getId());
                            break;
                    }
                }
            });
            mCommentDialog.show();
        }

        private void doDelCommentAction(int commentId) {
//            showProgressDialog();
            QuizReplyDelCommentAction action = QuizReplyDelCommentAction.newInstance(getActivity(), commentId);
            onNewRequestCall(action.request(new AHttpService.IResCallback<PbBean.PbResCommentDelComment>() {
                @Override
                public void onCallback(int resultCode, Response<PbBean.PbResCommentDelComment> response, PbBean.PbBaseServerInfo baseServerInfo) {
                    if (getView() != null) {
//                        closeProgressDialog();
                        if (HttpHelper.showError(getActivity(), resultCode, baseServerInfo, R.string.error_operation)) {
                            return;
                        }
                        requestData(true);
                    }
                }
            }));
        }

        private void showDelCommentDialog(final int commentId) {
            if (mDelCommentDialog == null) {
                mDelCommentDialog = new ConfirmDialog(getActivity(), getString(R.string.dialog_toast_del_comment), getString(R.string.guide_delcomment_cancel_btn), getString(R.string.guide_delcomment_sure_btn));
            }
            mDelCommentDialog.setCallbackListener(new ConfirmDialog.CallbackListener() {
                @Override
                public void clickNo() {
                }

                @Override
                public void clickYes() {
                    doDelCommentAction(commentId);
                }
            });
            mDelCommentDialog.show();
        }

        private void showCommentChoiceDialog(PbBean.PbBaseComment comment) {
            PbBean.PbUserSimple userInfo = comment.getUserInfo();
            if (userInfo.getUserId() != null && userInfo.getUserId().equals(ConfigUtils.getUserId(getContext()))) {
                showCommentChoiceDialog(comment, true);
            } else {
                showCommentChoiceDialog(comment, false);
            }
        }

        public void onEventMainThread(ReplyDetailItemClickEvent event) {
            ReplyDetailItem item = event.getItem();
            switch (item.itemType) {
                case ReplyDetailItem.TYPE_COMMENT_TXT:
                case ReplyDetailItem.TYPE_COMMENT_IMAGE:
                    if (ReplyDetailItemClickEvent.EVENT_COMMENT_ITEM_CLICK == event.getEvent()) {
                        showCommentChoiceDialog(item.comment);
                    }
                    break;
            }
        }

        public void onEventMainThread(DialogDismissEvent event){
//            cancelRequest();
        }

        private void requestData(final boolean refresh) {
            if (refresh && mAdapter.isEmpty()) {
                showProgressDialog();
            }
            int offset = refresh ? 0 : mAdapter.getCount();
            ReplyGetCommentListAction action = ReplyGetCommentListAction.newInstance(getActivity(), replyId, offset, mReplyType);
            onNewRequestCall(action.request(new AHttpService.IResCallback<PbBean.PbResCommentGetCommentList>() {
                @Override
                public void onCallback(int resultCode, Response<PbBean.PbResCommentGetCommentList> response, PbBean.PbBaseServerInfo baseServerInfo) {
                    if (getView() != null) {
                        closeProgressDialog();
                        if (HttpHelper.showError(getActivity(), resultCode, baseServerInfo, R.string.error_operation)) {
                            mDataBinding.commonListView.stopRefresh();
                            mDataBinding.commonListView.stopLoadMore();
                            return;
                        }
                        doLoadCommentListSuccess(refresh, response.body());
                    }
                }
            }));
        }

        private void doLoadCommentListSuccess(boolean refresh, PbBean.PbResCommentGetCommentList body) {
            if (body != null) {
                if (refresh) {
                    mAdapter.setData(ReplyDetailItem.convert(body.getCommentListList()));
                } else {
                    mAdapter.append(ReplyDetailItem.convert(body.getCommentListList()));
                }
                mDataBinding.cmtBarLayout.setVisibility(View.VISIBLE);
                mDataBinding.commonListView.setPullLoadEnable(body.getCommentListList().size() == getPageLength());
                mDataBinding.commonListView.stopRefresh();
                mDataBinding.commonListView.stopLoadMore();
            }
        }

        private void doLikeAction(final ReplyDetailEvent event) {
//            showProgressDialog();
            ReplyLikeCommentAction action = ReplyLikeCommentAction.newInstance(getActivity(), event.item.commentId);
            onNewRequestCall(action.request(new AHttpService.IResCallback<PbBean.PbResCommentLikeComment>() {
                @Override
                public void onCallback(int resultCode, Response<PbBean.PbResCommentLikeComment> response, PbBean.PbBaseServerInfo baseServerInfo) {
                    if (getView() != null) {
//                        closeProgressDialog();
                        if (HttpHelper.showError(getActivity(), resultCode, baseServerInfo, R.string.error_operation)) {
                            return;
                        }
                        doLikeSuccess(event);
                    }
                }
            }));
        }

        private void doLikeSuccess(ReplyDetailEvent e) {
            ReplyDetailItem detailItem = e.item;
            detailItem.isLikeComment = ReplyDetailEvent.EVENT_LIKE_COMMENT == e.getEvent();
            detailItem.commentLikeCount = ReplyDetailEvent.EVENT_LIKE_COMMENT == e.getEvent() ? e.item.commentLikeCount + 1 : e.item.commentLikeCount - 1;
            ReplyDetailItemClickEvent event = new ReplyDetailItemClickEvent(detailItem, ReplyDetailItemClickEvent.EVENT_COMMENT_LIKE_CLICK);
            EventBusUtil.post(event);
        }

        private View createHeaderView() {
            View headerView = getActivity().getLayoutInflater().inflate(R.layout.view_head_divider, null);
            return headerView;
        }

        private View.OnClickListener createOnCmtListener() {
            return new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mCmtDlg = new CommentDialog(v.getContext(), new CommentDialog.CallbackListener() {
                        @Override
                        public void onCmtSubmit(int commentId) {
                            onAddCommentAction(commentId);
                        }
                    });
                    mCmtDlg.show();
                }
            };
        }

        @Override
        public String getContent() {
            if (mCmtDlg != null) {
                return mCmtDlg.getContent();
            }
            return "";
        }

        @Override
        public List<UploadImage> getUploadImageList() {
            List<UploadImage> images = new ArrayList<>();
            if (mCmtDlg != null) {
                return mCmtDlg.getUploadImageList();
            }
            return images;
        }

        @Override
        public void setImageToken(UploadImage uploadImage) {
            if (mCmtDlg != null) {
                mCmtDlg.setImageToken(uploadImage);
            }
        }

        @Override
        public String getDesignerId() {
            return null;
        }

        @Override
        public BaseFragment getFragment() {
            return this;
        }

        @Override
        public void onHeadActionClick() {
        }

        @Override
        public void onAddCommentAction(int commentId) {
            mPresenter.onHeadActionClick(commentId);
        }

        @Override
        public void showDialogLoading() {
            if (mCmtDlg != null && mCmtDlg.isShowing()) {
                mCmtDlg.showProgressView();
            }
        }

        @Override
        public void closeDialogLoading() {
            if (mCmtDlg != null && mCmtDlg.isShowing()) {
                mCmtDlg.closeProgressView();
            }
        }

        @Override
        public void closeCmtDialog() {
            if (mCmtDlg != null && mCmtDlg.isShowing()) {
                mCmtDlg.dismiss();
                mCmtDlg = null;
            }
        }
    }
}
